package whf.framework.dao;

import java.util.ArrayList;
import java.util.List;

import whf.framework.util.BeanUtils;
import whf.framework.util.StringUtils;
import whf.framework.util.Utils;

/**
 * @author wanghaifeng
 *
 */
public class DaoHelper {

	/**
	 * 通过属性字符串搜索，字符串描述格式为：{property1::=::property1.value};{property2::>=::property2.value};{property3::<=::property3.value...}
	 * 各属性间关系为and,其中::中间::的是一元操作符
	 */
	public static Object[] buildSqlForFindByPropertyString(Class boClass, String queryString){
		StringBuffer sql = new StringBuffer();
		if(queryString.toLowerCase().indexOf("from") < 0 ){
			sql.append("from ").append(boClass.getName()).append(" t ");
		}
		Object[] paramValues = {};
		if(!StringUtils.isEmpty(queryString)){
			List<String[]> list = new ArrayList<String[]>();
			String[] props = StringUtils.split(queryString,"};{");
			for(String prop: props){
				String[] con = StringUtils.split(prop,"::");
				if(con.length != 3) continue;
				if(BeanUtils.hasProperty(boClass, con[0])){
					if(sql.indexOf("where") == -1){
						sql.append(" where ");
					}else{
						sql.append(" and ");
					}
					if(StringUtils.equalsIgnoreCase("like", con[1])){
						sql.append("t.").append(con[0]).append(" like ").append("%").append(con[2]).append("%");
					}else{
						list.add(con);
						sql.append("t.").append(con[0]).append(con[1]).append("?");
					}
				}
			}
			paramValues = new Object[list.size()];
			int count = 0;
			for(String[] con: list){
				paramValues[count] = Utils.getPropertyObject(boClass, con[0], con[2]);
				count ++;
			}
		}
		return new Object[]{sql, paramValues};
	}
	
	public static void main(String[] args) throws Exception{
		Object[] result = buildSqlForFindByPropertyString(whf.framework.entity.AbstractEntity.class, "{name::=::'a'};{id::=::1}");
		System.out.println(result[0]);
		System.out.println(result[1]);
		Object[] res = (Object[])result[1];
		for(Object o:res){
			System.out.println(o);
		}
	}
}
